package io.renren.modules.sys.utils;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;

public class OssUtil {

    private static Logger logger = LoggerFactory.getLogger(OssUtil.class);

    /* ***你的阿里云Access Key Id*** */
    private static String accessKeyId = "LTAI4GFM5ootW7dzBqxTCNMc";
    /* ***你的阿里云Access Key Secret*** */
    private static String accessKeySecret = "NgOJsldfpGU6yjsRgJN8oUwnlwu0fT";
    /* ***你的阿里云OSS BuckName*** */
    private static String bucketName = "xun-xxb";
    /* ***你的阿里云OSS 所属地区EndPoint*** */
    private static String ossEndpoint = "oss-cn-hangzhou.aliyuncs.com";
    /* ***你的阿里云OSS 对应绑定BuckName的域名,如果没有绑定请设置为null *** */
    private static String bindDomin = "https://xun-xxb.oss-cn-hangzhou.aliyuncs.com";
    private static int timeout = 5000;

    private static OSSClient ossClient;

    static {
        init();
    }

    public static synchronized void init() {
        if(ossClient != null){
            return;
        }
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(timeout);
        conf.setConnectionRequestTimeout(timeout);
        conf.setSocketTimeout(timeout);
        conf.setMaxErrorRetry(10);
        ossClient = new OSSClient("http://" + ossEndpoint, accessKeyId, accessKeySecret, conf);

        if(null != bindDomin && bindDomin.startsWith("http")){
            if(!bindDomin.endsWith("/")){
                bindDomin += "/";
            }
        }else{
            bindDomin = "http://" + bucketName + "." + ossEndpoint + "/";
        }
        logger.info("oss init");
    }

    public static void destroy() {
        if(ossClient != null){
            ossClient.shutdown();
            ossClient = null;
            logger.info("oss destory");
        }
    }

    /**
     * @Title: isExist
     * @Description: 判断key是否存在
     * @author Jecced
     * @param key
     * @return
     */
    public static boolean isExist(String key) {
        key = formatKey(key);
        return ossClient.doesObjectExist(bucketName, key);
    }

    /**
     * @Title: getSimplePutMD5
     * @Description: 获取key文件的md5
     * @author Jecced
     * @param key
     * @return
     */
    public static String getSimplePutMD5(String key){
        key = formatKey(key);
        boolean exists = isExist(key);
        if(exists){
            OSSObject object = ossClient.getObject(bucketName, key);
            ObjectMetadata meta = object.getObjectMetadata();
            String eTag = meta.getETag();
            return eTag;
        }
        return "";
    }

    /**
     * @Title: getFileSize
     * @Description: 获取文件大小
     * @author Jecced
     * @param key
     * @return
     */
    public static long getFileSize(String key){
        key = formatKey(key);
        if(isExist(key)){
            OSSObject object = ossClient.getObject(bucketName, key);
            ObjectMetadata metadata = object.getObjectMetadata();
            long contentLength = metadata.getContentLength();
            return contentLength;
        }
        return -1;
    }

    /**
     * @Title: getObjeInputStream
     * @Description: 从OSS中获取对象输入流
     * @author Jecced
     * @param key
     * @return
     */
    public static InputStream getObjeInputStream(String key) {
        key = formatKey(key);
        if(!isExist(key)){
            return null;
        }
        OSSObject obj = ossClient.getObject(bucketName, key);
        return obj.getObjectContent();
    }

    /**
     * @Title: downObj
     * @Description: 文件下载到指定File对象
     * @author Jecced
     * @param key
     * @param file
     */
    public static void downObj(String key, File file) {
        key = formatKey(key);
        InputStream is = getObjeInputStream(key);

        FileOutputStream fos = null;
        try{
            fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024 * 10];
            int len = -1;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.safeClose(fos);
            IOUtils.safeClose(is);
        }
    }

    /**
     * 简单上传OSS文件
     * @param name 文件名
     * @param file File对象
     * @param path 存储路径
     * @param contentType 手动设置文件类型：image/png
     * @return OSS文件Key的路径
     */
    public static String uploadObj(String path, String name, File file, String contentType) {
        String key = path + "/" + name;
        key = formatKey(key);
        ObjectMetadata meta = null;
        if (contentType != null) {
            meta = new ObjectMetadata();
            meta.setContentType(contentType);
        }
        ossClient.putObject(bucketName, key, file, meta);

        return bindDomin + key;
    }

    /**
     * @Description: uploadStream 上传一个is流
     * @author Jecced
     * @param path     oss路径
     * @param name     文件名
     * @param is       is输入流
     * @param contentType 手动设置文件类型：image/png
     * @return
     */
    public static String uploadStream(String path, String name, InputStream is, String contentType) {
        String key = path + "/" + name;
        key = formatKey(key);
        ObjectMetadata meta = null;
        if (contentType != null) {
            meta = new ObjectMetadata();
            meta.setContentType(contentType);
        }
        ossClient.putObject(bucketName, key, is, meta);
        return bindDomin + key;
    }


    public static String uploadObj(String path, String name, File file) {
        return uploadObj(path, name, file, null);
    }

    /**
     * 删除指定key
     */
    public static void delKey(String key) {
        ossClient.deleteObject(bucketName, key);
    }

    /**
     * 格式化key的格式
     */
    private static String formatKey(String key) {
        if(!key.startsWith("/") && -1 == key.indexOf('\\')){
            return key;
        }
        if (key != null) {
            key = key.replaceAll("\\\\", "/");
        }
        while (key != null && key.startsWith("/")) {
            key = key.substring(1, key.length());
        }
        return key;
    }

    /**
     * 根据url格式化得到key
     */
    public static String UrlParseKey(String url){
        try{
            return url.substring(url.indexOf('/', 7) + 1);
        }catch (Exception e) {
            return "";
        }
    }

    /**
     * 根据key,url获取文件名
     */
    public static String getFileName(String key){
        return key.substring(key.lastIndexOf('/') + 1);
    }

    /**
     * @Title: rename
     * @Description: oss key重命名
     * @author Jecced
     * @param oldKey
     * @param newKey
     * @return
     */
    public static boolean rename(String oldKey, String newKey){
        oldKey = formatKey(oldKey);
        newKey = formatKey(newKey);
        if(!isExist(oldKey)){
            return false;
        }
        if(isExist(newKey)){
            return false;
        }
        ossClient.copyObject(bucketName, oldKey, bucketName, newKey);
        ossClient.deleteObject(bucketName, oldKey);
        return true;
    }

    /**
     * @Title: listKey
     * @Description: 遍历迭代出路径中的所有key
     * @author Jecced
     * @param path 路径,前缀
     */
    public static List<String> listKey(String path){
        List<String> list = new ArrayList<>();
        String nextMarker = null;
        ObjectListing objectListing = null;
        List<OSSObjectSummary> sums = null;
        do {
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
            listObjectsRequest.withMarker(nextMarker)
                    .withMaxKeys(1000)//每次最大返回复合条件的对象,最大1000
                    .setPrefix(path);
            objectListing = ossClient.listObjects(listObjectsRequest);
            sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                list.add(s.getKey());
            }
            nextMarker = objectListing.getNextMarker();
        } while (objectListing.isTruncated());
        return list;
    }

    /**
     * @Title: delKeys
     * @Description: 删除指定的所有key
     * @author Jecced
     * @param keys 所有要被删除的key集合
     */
    public static void delKeys(List<String> keys){
        DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(
                new DeleteObjectsRequest(bucketName).withKeys(keys));
        deleteObjectsResult.getDeletedObjects();
    }

    /**
     * @Title: cleanPath
     * @Description: 删除/清空一整个路径内的所有文件
     * @author Jecced
     * @param path
     */
    public static void cleanPath(String path){
        List<String> keys = listKey(path);
        delKeys(keys);
    }

}
